import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from "@/views/Index";
import Home from "@/views/common/Home";
import Blank from "@/views/Blank";
const BlogEdit = ()=>import("@/views/BlogEdit");    //懒加载方式引入
const BlogDetail = ()=>import("@/views/BlogDetail")
const Statistics = ()=>import("@/views/Statistics");
const NotFound = ()=>import("@/views/NotFound");
const UserCenter = ()=>import("@/views/UserCenter")
import store from "../store";
import axios from "../axios";   //引入自己创建的axios，这样会按自己写的代码进行拦截


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: {name:'Index'}
  },
  {
    path: '',
    name: '',
    component: Home,
    children: [
      {
        path: '/index',
        name: 'Index',
        component: Index
      },
      {
        path: '/blog/edit',
        name: 'BlogEdit',
        component: BlogEdit,
        meta: {
          //这里可以存放一些数据
        }
      },
      {
        path: '/blog/:blogId',
        name: 'BlogDetail',
        component: BlogDetail
      },
      {
        path: '/userCenter',
        name: 'UserCenter',
        component: UserCenter,
      },
      {
        path: '/blank',
        name: 'Blank',
        component: Blank
      },
      {
        path: '/statistics',
        name: Statistics,
        component: Statistics
      },
      {
        path: '/*',
        name: NotFound,
        component: NotFound
      }
    ]
  }
]

//解决导航菜单中重复点击相同路由的报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location) {
  return originalPush.call(this,location).catch(err => err)
}
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function (location) {
  return originalReplace.call(this,location).catch(err => err)
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//每次路由之前都会执行
router.beforeEach((to, from, next) => {

  //根据此判断一次访问量，存到后端
  if(!sessionStorage.getItem('vf')){
    sessionStorage.setItem('vf','er11dftr25w9epohyb1')
    axios.get('/visit/add').then(res=>{
    })
  }
  store.state.activeIndex = to.path   //更新头部导航栏菜单被选中索引
  store.state.router_loading = true   //路由时显示Home页面的加载标志

  next();
})

router.afterEach((to,from)=>{
  store.state.router_loading = false   //路由结束时关闭Home页面的加载标志
})

export default router
